package com.sk.waste.app.activitys

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.Gravity
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.lc.smc.lib.annotations.LCBindView
import com.lc.smc.lib.interfaces.LCInterface
import com.lc.smc.lib.utils.LCBaseUtil
import com.lc.smc.lib.utils.LCSPUtil
import com.sk.waste.app.R
import com.sk.waste.app.adapters.AlbumAdapter
import com.sk.waste.app.application.MyApplication
import com.sk.waste.app.bases.BaseActiivity
import com.sk.waste.app.config.AppConfig
import com.sk.waste.app.config.NetWorkConfig
import com.sk.waste.app.utils.OkHttpUtil
import com.sk.waste.app.views.SkAlertDialog
import com.sking.album.activitys.ShowLargePicActivity
import com.sking.album.model.SKRImageModel
import com.sking.album.utils.SKRPhotoSelectUtil
import com.sking.album.view.AlbumSelectPopuWindow
import okhttp3.Call
import org.json.JSONArray
import org.json.JSONObject
import java.io.IOException


/**
 *  @time 2025/10/22  10:32
 *  @author Im_jingwei
 *  @desc 发布信息
 */
class PushActivity : BaseActiivity() {

    @LCBindView(R.id.ac_push_edittext)
    private lateinit var ettContent: EditText

    @LCBindView(R.id.ac_push_recyler)
    private lateinit var mRecyclerView: RecyclerView

    private var mAdapter: AlbumAdapter? = null
    private val mList = arrayListOf<SKRImageModel>()
    private val tempList = arrayListOf<SKRImageModel>()
    private var maxCount = 4
    private var cameraTyoe = 0
    private var albumTyoe: Int = 0
    private var upload_index = 0
    private lateinit var photoSelectUtil: SKRPhotoSelectUtil
    private lateinit var albumSelectPopuWindow: AlbumSelectPopuWindow
    private var pushDialog: SkAlertDialog? = null
    private val upList = arrayListOf<String>()

    override fun onCreate(savedInstanceState: Bundle?) {
        setContentView(R.layout.activity_push)
        super.onCreate(savedInstanceState)
        setBack()
        setTitleView("发布信息")
        setSubmit("发布") {
            val content = ettContent.text.toString()
            if (!LCBaseUtil.isNull(content)) {
                showPushAlert()
            } else {
                LCBaseUtil.showToast(mContext, "请输入内容！")
            }
        }
        initRecyclerView()
    }

    private fun initRecyclerView() {
//        mRecyclerView.setHasFixedSize(true)
        mRecyclerView.setLayoutManager(GridLayoutManager(mContext, 4))

        mAdapter = AlbumAdapter(mContext, 1, mList, object : AlbumAdapter.OnItemClickLitener {
            override fun onItemClick(position: Int) {
                hideKeyboard()
                if (position == mList.size) {
                    photoSelectUtil.setSelectSize(maxCount - mList.size)
                    if (mList.size < maxCount)
                        albumSelectPopuWindow.showAtLocation(ettContent, Gravity.BOTTOM, 0, 0)
                    else
                        showToast("最多可上传4张照片")
                } else {
                    val sIt = Intent(mContext, ShowLargePicActivity::class.java)
                    sIt.putExtra("position", position)
                    sIt.putExtra("images", mList)
                    mContext.startActivity(sIt)
                }
            }

            override fun onItemDelete(position: Int) {
                mList.removeAt(position)
                mAdapter!!.notifyDataSetChanged()
            }
        })
        //        mRecyclerView.addItemDecoration(new ItemDecoration(10, 10));
        mRecyclerView.setAdapter(mAdapter)

        photoSelectUtil = SKRPhotoSelectUtil.getInstance(this)
        photoSelectUtil.setSelectSize(maxCount)
        photoSelectUtil.setOnBackClick { string ->
            Log.d("LCLOG_AlbumSelect", string!!)
            upload_index = 0
            val albumModel = SKRImageModel()
            albumModel.imgurl = string
            albumModel.imgurlbig = string
            mList.add(albumModel)
            mAdapter!!.notifyDataSetChanged()
        }

        albumSelectPopuWindow = AlbumSelectPopuWindow()
        albumSelectPopuWindow.init(mContext)
        albumSelectPopuWindow.setPopuOnclickListener { view ->
            albumSelectPopuWindow.dismiss()
            when (view?.id) {
                R.id.popu_take_photo_compress -> {
                    photoSelectUtil.camera()
                }

                R.id.popu_take_album_press -> {
                    photoSelectUtil.album()
                }
            }
        }
    }

    /**
     *  @time 2025/1/21  17:42
     *  @author Im_jingwei
     *  @desc 裁剪图片选择回调
     */
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != RESULT_OK)
            return
        var imgPath = ""
        when (requestCode) {
            1 -> {
//                photoSelectUtil.dealAlbum(data)
                imgPath = photoSelectUtil.getFilePath(data)
            }

            2 -> {
//                photoSelectUtil.dealCamera() //拍照可编辑不压缩
                imgPath = photoSelectUtil.filePath
            }

            3 -> {
//                val currentPicturePath = photoSelectUtil.filePath
//                val pith = photoSelectUtil.tempPath
//                val bitmap = BitmapFactory.decodeFile(pith)
//                imgAvatar.setImageBitmap(bitmap)
//                uploadAttach(pith)
            }

            else -> {}
        }
        val albumModel = SKRImageModel()
        albumModel.imgurl = imgPath
        albumModel.imgurlbig = imgPath
        mList.add(albumModel)
        mAdapter!!.notifyDataSetChanged()
    }

    /**
     *  @time 2025/5/9  17:53
     *  @desc 信息发布
     */
    private fun showPushAlert() {
        if (pushDialog == null) {
            pushDialog = SkAlertDialog(mContext)
        }
        pushDialog!!.setTitleAndContent(
            "用户须知",
            "    尊敬的用户，为了维护一个健康、可信的空间环境，请您在发布信息时,确保内容真实、合法、有效。\n    请知悉，您是信息内容的唯一责任人。平台仅提供信息展示空间，无法对信息进行审核。因此，因信息内容产生的任何法律风险，都需要由您自行承担。感谢您的理解与配合！确认要发布此条信息吗？"
        )
        pushDialog!!.setOnclickListener(object : LCInterface.LcOnPnButtonClickLitener {
            override fun onNegetiveClick(vararg args: Any?) {
            }

            override fun onPositiveClick(vararg args: Any?) {
                upList.clear()
                showProgress("附件上传中请稍后...")
                if (mList.size != 0) {
                    for (img in mList) {
                        uploadAttach(img.imgurl)
                    }
                } else {
                    push()
                }
            }
        })
        pushDialog!!.setContentCenter(false)
        pushDialog!!.showExpend()
    }

    /**
     *  @time 2024/5/7  11:29
     *  @desc 发布
     *  @param url
     */
    private fun push() {
        if (upList.size < mList.size) {
            return
        }
        runOnUiThread {
            cancleProgress()
            showProgress("正在发布...")
        }

        val httpUtil = OkHttpUtil()
        val token = LCSPUtil[mContext, AppConfig.SP_ACCESS_TOKEN]
        val url = NetWorkConfig.NET_URL_ROOT + NetWorkConfig.NET_URL_SPACE_PUSH
        val user = MyApplication.instance.getUserInfo()
        val jsonObject = JSONObject()
        val city = MyApplication.instance.getLocaiton()
        val content = ettContent.text.toString()
        jsonObject.put("publishLocation", city)
        jsonObject.put("infoContent", content)
        jsonObject.put("contactInfo", user!!.phone)
        val imgArray = JSONArray()
        for (url in upList) {
            imgArray.put(JSONObject().put("imageUrl", url))
        }
        jsonObject.put("imageList", imgArray)
        httpUtil.httpRequest(url, token, jsonObject.toString(), object : LCInterface.LcCallBackListener {
            override fun onFailure(call: Call, e: IOException) {
                cancleProgress()
                LCBaseUtil.showToast(mContext, "发布失败，" + e.message)
            }

            @Throws(IOException::class)
            override fun onSuccess(call: Call, response: String) {
                try {
                    cancleProgress()
                    val jsonObject = JSONObject(response)
                    val success = jsonObject.getBoolean("success")
                    val msg = jsonObject.getString("message")
                    if (success) {
                        showToast("发布成功！")
                        runOnUiThread {
                            setResult(RESULT_OK,intent.putExtra("push_reust",true))
                            finish()
                        }
                    } else {
                        LCBaseUtil.showToast(mContext, "发布失败，$msg")
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    LCBaseUtil.showToast(mContext, "发布失败，" + e.message)
                }
            }
        })
    }


    /**
     *  @time 2024/11/15  11:16
     *  @author Im_jingwei
     *  @desc 上传附件
     */
    private fun uploadAttach(filePath: String?) {
        val httpUtil = OkHttpUtil()
        val url = NetWorkConfig.NET_URL_ROOT + NetWorkConfig.NET_URL_UPLOAD
        val token = LCSPUtil[mContext, AppConfig.SP_ACCESS_TOKEN]
        val params = HashMap<String, String>()
        httpUtil.httpRequestFile(url, token!!, "image", filePath!!, params, object : LCInterface.LcCallBackListener {
            override fun onSuccess(call: Call, response: String) {
                val jsonObject = JSONObject(response)
                val msg = jsonObject.getString("msg")
                val imgurl = jsonObject.getString("location")
                if ("上传成功" == msg) {
                    upList.add(NetWorkConfig.NET_URL_IMG_ROOT + imgurl)
                    push()
                }
                Log.d("LCLOG_CRASH", "附件文件已上传！---------------${response}")
            }

            override fun onFailure(call: Call, e: IOException) {
                showToast("图片上传失败,请重试！")
                upList.clear()
                Log.d("LCLOG_CRASH", "附件文件上传失败！---------------")
            }
        })
    }

}